/**
 * @author Yang
 * @date 2021/10/15
 * @description: java后台重写排序，传参格式为：sortList:[{ field: string, ascending: Boolean }]，且可多字段排序
 */
import { ref } from 'vue'

export interface SortItem {
  field: string
  ascending: boolean
}

export function useSort() {
  const sortList = ref<SortItem[]>([])

  const handleSort = (data: { prop: string; order: string | null }) => {
    let flag = true
    
    for (let i = 0; i < sortList.value.length; i++) {
      if (sortList.value[i].field === data.prop) {
        flag = false
        if (data.order === 'ascending') {
          sortList.value[i].ascending = true
          const obj = sortList.value[i]
          sortList.value.splice(i, 1)
          sortList.value.unshift(obj)
        }
        if (data.order === 'descending') {
          sortList.value[i].ascending = false
          const obj = sortList.value[i]
          sortList.value.splice(i, 1)
          sortList.value.unshift(obj)
        }
        if (data.order === null) {
          sortList.value.splice(i, 1)
        }
      }
    }

    if (flag) {
      sortList.value.unshift({
        field: data.prop,
        ascending: data.order !== 'descending'
      })
    }

    return sortList.value
  }

  return {
    sortList,
    handleSort
  }
}